﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Web.Script.Serialization;

namespace com.baidu.ai
{
    public static class AccessToken

    {
        // 调用getAccessToken()获取的 access_token建议根据expires_in 时间 设置缓存
        // 返回token示例
        public static String TOKEN = "24.adda70c11b9786206253ddb70affdc46.2592000.1493524354.282335-1234567";

        // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
        private static String clientId = "3GNW7bqTX02s0B1gg9EAgyna";
        // 百度云中开通对应服务应用的 Secret Key
        private static String clientSecret = "WbGUZ3205RVOIw9XoMBmUCwScZMnvet1";

        public static String getAccessToken()
        {
            String authHost = "https://aip.baidubce.com/oauth/2.0/token";
            HttpClient client = new HttpClient();
            List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
            paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
            paraList.Add(new KeyValuePair<string, string>("client_id", clientId));
            paraList.Add(new KeyValuePair<string, string>("client_secret", clientSecret));

            HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
            String result = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine(result);


            //获取返回的字符串
            //string test = AccessToken.getAccessToken();
            //Response.Write(test + "<br/>");


            //获取返回的Access_Token
            string Access_Token = "";
            JavaScriptSerializer Jss = new JavaScriptSerializer();
            Dictionary<string, object> DicText = (Dictionary<string, object>)Jss.DeserializeObject(result);
            if (!DicText.ContainsKey("access_token"))
            {
                Access_Token = "获取Access_Token失败";
            }
            else
            {
                Access_Token = DicText["access_token"].ToString();
            }

            //Session["Token"] = Access_Token;
            //Response.Write(Access_Token);
            return Access_Token;
        }
    }
}
